<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="材料名称" prop="materialName">
        <el-input
          v-model="queryParams.materialName"
          placeholder="请输入材料名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:template:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:template:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:template:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:template:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模板ID" align="center" prop="templateId" />
      <!-- <el-table-column label="材料类型" align="center" prop="materialType" /> -->
      <el-table-column label="材料名称" align="center" prop="materialName">
        <template slot-scope="scope">
          <a 
            href="javascript:void(0)" 
            @click="handleDownload(scope.row)" 
            style="text-decoration: underline; color: #409EFF; cursor: pointer;"
          >
            {{ scope.row.materialName }}
          </a>
        </template>
      </el-table-column>
      <!-- <el-table-column label="模板文件URL" align="center" prop="templateUrl" /> -->
      <el-table-column label="材料说明" align="center" prop="materialDesc" />
      <!-- <el-table-column label="状态" align="center" prop="status" /> -->
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:template:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:template:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改党员材料模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="材料名称" prop="materialName">
          <el-input v-model="form.materialName" placeholder="请输入材料名称" />
        </el-form-item>
        <el-form-item label="模板文件" prop="templateUrl">
          <el-upload
            ref="upload"
            :limit="1"
            accept=".doc,.docx,.xls,.xlsx,.pdf"
            :action="uploadFileUrl"
            :headers="uploadHeaders"
            :file-list="fileList"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">支持doc/docx/xls/xlsx/pdf格式，文件大小不超过10MB。修改时删除旧文件可上传新文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="材料说明" prop="materialDesc">
          <el-input v-model="form.materialDesc" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTemplate, getTemplate, delTemplate, addTemplate, updateTemplate } from "@/api/system/template"
import { getToken } from "@/utils/auth"

export default {
  name: "Template",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 党员材料模板表格数据
      templateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 上传文件地址
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      // 上传的请求头
      uploadHeaders: { Authorization: "Bearer " + getToken() },
      // 文件列表
      fileList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialType: null,
        materialName: null,
        templateUrl: null,
        materialDesc: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        materialType: [
          { required: true, message: "材料类型不能为空", trigger: "change" }
        ],
        materialName: [
          { required: true, message: "材料名称不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询党员材料模板列表 */
    getList() {
      this.loading = true
      listTemplate(this.queryParams).then(response => {
        this.templateList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        templateId: null,
        materialType: null,
        materialName: null,
        templateUrl: null,
        materialDesc: null,
        status: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.fileList = []
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.templateId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加党员材料模板"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const templateId = row.templateId || this.ids
      getTemplate(templateId).then(response => {
        this.form = response.data
        // 如果有模板文件URL，设置文件列表
        if (this.form.templateUrl) {
          this.fileList = [{
            name: this.form.materialName || '模板文件',
            url: this.form.templateUrl
          }]
        }
        this.open = true
        this.title = "修改党员材料模板"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.templateId != null) {
            updateTemplate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addTemplate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const templateIds = row.templateId || this.ids
      this.$modal.confirm('是否确认删除党员材料模板编号为"' + templateIds + '"的数据项？').then(function() {
        return delTemplate(templateIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/template/export', {
        ...this.queryParams
      }, `template_${new Date().getTime()}.xlsx`)
    },
    /** 下载模板文件 */
    handleDownload(row) {
      if (!row.templateUrl) {
        this.$modal.msgWarning("该材料没有模板文件")
        return
      }
      // 创建隐藏的a标签进行下载
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = row.templateUrl
      link.download = row.materialName || '模板文件'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    /** 文件上传前的校验 */
    beforeUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) {
        this.$modal.msgError("文件大小不能超过10MB!")
        return false
      }
      const fileExt = file.name.substring(file.name.lastIndexOf('.') + 1)
      const validExt = ['doc', 'docx', 'xls', 'xlsx', 'pdf']
      if (!validExt.includes(fileExt.toLowerCase())) {
        this.$modal.msgError("只能上传doc/docx/xls/xlsx/pdf格式的文件!")
        return false
      }
      return true
    },
    /** 文件上传成功 */
    handleUploadSuccess(response, file, fileList) {
      if (response.code === 200) {
        this.form.templateUrl = response.url
        this.$modal.msgSuccess("上传成功")
      } else {
        this.$modal.msgError(response.msg || "上传失败")
        // 移除上传失败的文件
        const index = fileList.indexOf(file)
        if (index > -1) {
          fileList.splice(index, 1)
        }
      }
    },
    /** 文件上传失败 */
    handleUploadError(err, file, fileList) {
      this.$modal.msgError("上传失败，请重试")
      this.fileList = []
    },
    /** 删除文件 */
    handleRemove(file, fileList) {
      this.form.templateUrl = null
    }
  }
}
</script>
